import { Component, OnInit, Injectable, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { OptionItem } from '@iux/live';


@Injectable()
export class DemoService {

  length = 400;
  users: OptionItem[];

  constructor() {
    this.users = this.initUser();
  }

  getUsers(data: string = '') {
    const users = this.users.filter(item => item.label.toLowerCase().includes(data.toLowerCase()));
    return of(users).pipe(delay(300));
  }

  initUser() {
    const users = Array.from({length: this.length}).map((item, key) => {
      return { label: `user${key}`, age: 10 + key, expand: false, random: parseInt(Math.random() * 100 + '',10), isLeaf: true };
    });
    return users;
  }
}

@Component({
  selector: 'app-demo9',
  templateUrl: './demo9.component.html',
  styles: [],
  providers: [DemoService],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class Demo9Component implements OnInit {

  data: OptionItem[];
  value: {[key: string]: any};
  index = 0;
  selectedValue;

  constructor(
    private demoService: DemoService,
    private cdr: ChangeDetectorRef
  ) { }

  ngOnInit() {
    this.initAsyncData();
  }

  initAsyncData() {
    this.getUsers();
  }

  getUsers(data?: string) {
    this.demoService.getUsers(data).subscribe(res => {
      this.data = res;
      this.cdr.markForCheck();
    });
  }

  filterChange(value: string) {
    this.getUsers(value);
  }
}
